import preferences from '@ohos.data.preferences'
import { baseInfo } from '../BasicConstant'
import { ModelStore } from './ModelStore'

export class DataStore {
  private pre: preferences.Preferences
  static instance: DataStore = new DataStore()

  private constructor() {
    this.pre = ModelStore.find<preferences.Preferences>(baseInfo.preferences)
  }

  /**
   * 保存
   * @param key
   * @param value
   * @returns
   */
  async put(key: string, value: preferences.ValueType): Promise<void> {
    await this.pre.put(key, value)
    await this.pre.flush()
  }

  /**
   * 读取数据
   * @param key
   * @returns
   */
  async getString(key: string): Promise<string> {
    return (await this.pre.get(key, "")).toString()
  }

  /**
   * 删除
   * @param key
   * @returns
   */
  async delete(key: string): Promise<void> {
    await this.pre.delete(key)
    await this.pre.flush()
  }

  /**
   * 清除数据
   * @returns
   */
  async clear(): Promise<void> {
    await this.pre.clear()
    await this.pre.flush()
  }
}